package com.sqn.seckill.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * description: Json工具类
 *
 * @author sqn
 * @version 1.0
 * @date 2021/4/29 0029 下午 2:33
 */
public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * description: 将对象转换成Json字符串
     *
     * @param obj
     * @return: java.lang.String
     * @author sqn
     * @date: 2021/6/29 0029 下午 2:36
     */
    public static String object2JsonStr(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * description: 将字符串转换成对象
     *
     * @param jsonStr
     * @param clazz
     * @return: T
     * @author sqn
     * @date: 2021/6/29 0029 下午 2:43
     */
    public static <T> T jsonStr2Object(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr.getBytes("UTF-8"), clazz);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * description: 将Json数据转换成pojo对象List
     *
     * @param jsonStr
     * @param beanType
     * @return: java.util.List<T>
     * @author sqn
     * @date: 2021/6/29 0029 下午 2:46
     */
    public static <T> List<T> jsonToList(String jsonStr, Class<T> beanType) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = objectMapper.readValue(jsonStr, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
